package com.data.unityplugin_market.business.shoppingcart

import android.databinding.DataBindingUtil
import android.os.Bundle
import android.os.Message
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import com.alipay.sdk.app.PayTask
import com.data.unityplugin_market.base.BaseActivity
import com.data.unityplugin_market.base.BaseDataBindingAdapter
import com.data.unityplugin_market.base.BaseResp
import com.data.unityplugin_market.config.HttpConfig
import com.data.unityplugin_market.model.req.*
import com.data.unityplugin_market.model.resp.RespGetShoppingCartList
import com.data.unityplugin_market.network.NetWorkConfig
import com.data.unityplugin_market.network.RetrofitService
import com.data.unityplugin_market.payment.test.AliPayConfig.APPID
import com.data.unityplugin_market.payment.test.AliPayConfig.RSA2_PRIVATE
import com.data.unityplugin_market.payment.test.OrderInfoUtil2_0

import com.data.unityplugin_market.view.PaymentDialog
import com.data.unityplugin_market.viewmodel.ShoppingCartActVM
import com.data.unityplugin_market.viewmodel.ShoppingCartItemVM
import com.data.unityplugin_market_lib.BR
import com.data.unityplugin_market_lib.R
import com.data.unityplugin_market_lib.databinding.ActivityShoppingCartBinding
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class ShoppingCartActivity : BaseActivity(), CompoundButton.OnCheckedChangeListener, ShoppingCartItemVM.OnItemModifyClick {

    /**
     *
     */
    override fun onModify(vm: ShoppingCartItemVM) {
        updateAllPrice()
        var req = ReqUpdateGoodsCount()
        req.buyNum = vm.goodsTotal.get() + ""
        req.itemId = vm.itemID.get() + ""
        req.userId = HttpConfig.USER_ID


        NetWorkConfig.instance.retrofit.create(RetrofitService::class.java)
                .updateGoodsCount(req, HttpConfig.UPDATE_GOODS_COUNT, HttpConfig.getBaseKeyMap())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).doOnSubscribe {}
                .subscribe({

                }, {

                })

    }

    fun updateAllPrice() {
        var allPrice = 0.0
        for (i in 0 until shoppingCarListItem.size) {


            var price = java.lang.Double.parseDouble(shoppingCarListItem[i].goodsPrice.get());
            var total = Integer.parseInt(shoppingCarListItem[i].goodsTotal.get());
            allPrice += (price * total)
        }
        vm!!.total.set(allPrice.toString())

    }


    /**
     *s
     */
    var shoppingCarListItem = ArrayList<ShoppingCartItemVM>()

    var binding: ActivityShoppingCartBinding? = null;

    var vm: ShoppingCartActVM? = null;

    var adapter: BaseDataBindingAdapter<ShoppingCartItemVM>? = null;


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_shopping_cart)
        vm = ShoppingCartActVM(this)
        binding!!.shoppingCarActVM = vm;





        getShoppingCartList()
        //init()


    }


    fun getTestBill(): String {
        val rsa2 = RSA2_PRIVATE.length > 0
        val params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2)
        val orderParam = OrderInfoUtil2_0.buildOrderParam(params)

        val privateKey = if (rsa2) RSA2_PRIVATE else ""
        val sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2)
        return orderParam + "&" + sign
    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        updateStatus(isChecked)
    }


    private fun deleteItem() {
        var y: Int? = 0

        var removeIds = ""

        for (i in 0 until shoppingCarListItem.size) {
            var bean = shoppingCarListItem[i - y!!]
            if (bean.checkStatus.get() == true) {
                removeIds += shoppingCarListItem[i - y].goodsID.get() + ","
                shoppingCarListItem.removeAt(i - y)
                y++
            }
        }
        adapter!!.notifyDataSetChanged()

        var req = ReqDeleteGoods()
        req.id = removeIds;
        NetWorkConfig.instance.retrofit.create(RetrofitService::class.java)
                .deleteGoods(req, HttpConfig.DELETE_GOODS, HttpConfig.getBaseKeyMap())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).doOnSubscribe {}
                .subscribe({

                }, {

                })

        vm!!.allCount.set("共" + shoppingCarListItem.size + "件商品 共计:")
        updateAllPrice()
    }

    /**
     *
     */
    fun paymentClick(view: View) {
        var activity = this
        if (vm?.isModify?.get()!!) {
            deleteItem()
        } else {
            var dialog = PaymentDialog(this, R.style.dialogstyle)
            dialog.apply {
                    setListenerCallBack(object : PaymentDialog.PaymentListener{
                        override fun onPayClick(type: Int) {


                            object : Thread() {
                                override fun run() {
                                    val alipay = PayTask(activity)
                                    val result = alipay.payV2(getTestBill(), true)
                                }
                            }.start()
                            dismiss()
                        }
                    })
            }
            dialog.show()
        }

    }

    /**
     * 编辑按钮点击
     */
    fun modifyClick(view: View) {
        vm!!.isModify.set(vm!!.isModify.get() != true)

    }


    fun updateStatus(data: Boolean) {

        for (i in 0 until shoppingCarListItem.size) {
            shoppingCarListItem[i].checkStatus.set(data)
        }
        adapter?.notifyDataSetChanged()

    }

    private fun getShoppingCartList() {
        var req = ReqGetShoppingCartList()
        req.userId = "1"
        NetWorkConfig.instance.retrofit.create(RetrofitService::class.java)
                .findShoppingCartList(req, HttpConfig.GET_SHOPPINGCART_LIST, HttpConfig.getBaseKeyMap())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).doOnSubscribe {

                    print("call")
                }
                .subscribe({
                    displayList(it)
                }, {

                })

    }

    private fun displayList(it: BaseResp<RespGetShoppingCartList>) {

        if (it.results!!.result.size == 0) {
            vm!!.isEmpty.set(true)
        }

        for (i in 0 until it.results!!.result.size) {
            var item = ShoppingCartItemVM();
            item.goodsDescription.set(it!!.results!!.result[i].itemTitle)
            item.goodsModel.set("21321321")
            item.goodsID.set(it!!.results!!.result[i].id)
            item.goodsPrice.set(it!!.results!!.result[i].itemPrice)
            item.goodsTotal.set(it!!.results!!.result[i].buyNum)
            item.itemID.set(it!!.results!!.result[i].itemId)
            item.listener = this
            shoppingCarListItem!!.add(item)
        }


        vm!!.allCount.set("共" + shoppingCarListItem.size + "件商品 共计:")

        // updateAllPrice()

        adapter = BaseDataBindingAdapter(this, layoutInflater, R.layout.widget_shopping_cart_list_item, BR.shoppingCartItemVM, this.shoppingCarListItem)
        binding!!.recycleShoppingCart.layoutManager = LinearLayoutManager(this)
        binding!!.recycleShoppingCart.adapter = adapter;
        binding!!.cbAllSelector.setOnCheckedChangeListener(this)

        updateAllPrice()
    }

    private fun init() {
        var req = ReqLogin()
        NetWorkConfig.instance.retrofit.create(RetrofitService::class.java)
                .loginBase(req, HttpConfig.LOGIN)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).doOnSubscribe {
                    print("call")
                }
                .subscribe({


                }, {
                    Log.d("acthome", "msg:" + it.message)
                })


    }
}